\chapter{Implementation}
\label{chap:impl}

In this chapter we discuss the implementation of the developed software and examine
its behavior for different scenarios.
 
As mentioned earlier, our system can be divided into two clients with a common server. 
The most important part of the server is its database and the user model. The latter describes how users, user groups and their privileges are handled by our system. We do not present each function of the server explicitly, as these are presented in the description of the clients. 
The first client is the improved ELBS viewer. We give an overview of the improvements and their purpose in Section~\ref{sec:elbsviewer}.
Towards the end of the section, we offer an  outline of the main classes involved in the development of the program.
The second client is the download portal. We give an overview of its functionalities in Section~\ref{sec:uidp}. 

\section{Data Persistence}
\label{sec:datapersistance}
Data persistence is a major part of our system. 
In our implementation, we achieve data persistence mainly by using a relational database.
A lot of our efforts were concentrated in developing a database schema that is on the one hand flexible, 
i.e., easy to incorporate new functionalities to the system, and on the other hand robust, i.e., 
ensuring that adding new tables and rows to the database would not crash the system.  

In this section we discuss how we extended the initial database of the ELBS 1.0 viewer, in order
to implement the new functionalities required by ELBS 1.1 and the download portal. Then we go
over each table and describe its purpose. In addition, we present how the database schema was 
realized in Hibernate using JAVA objects, instead of SQL queries.

Our new database schema is shown in Figure~\ref{fig:db}. 
We use a entity-relationship diagrams (ERD) to describe our database model. 
In the ERD primary keys are notated as \emph{PK} and 
foreign keys are notated as \emph{FK} .  

\begin{figure}[htp]
	\begin{center}
		\includegraphics[width=\textwidth]{./img/db.pdf}
		\caption{Database ER-Diagram}
		\label{fig:db}
	\end{center}
\end{figure}

\subsubsection{User Table}
The most important new table in the database is the user table. It only stores a user name and a user type. The latter is used is used to indicate whether the user credentials are stored in the local database or in the LDAP server of the university. The first time an LDAP user logs-in to our system, he\footnote{"He" should be read as "he or she" throughout this thesis.}
is automatically stored in the database, and receives a unique user id, which is necessary in order to keep track of all the printed/downloaded pages or documents. 

\subsubsection{External User Table}
This table is used to store user information, such as password and email for each user who does not have a university account. 
Note that we only store a hash value of the password. For this purpose we use the Whirlpool cryptographic hash function~\cite{wwhirlpool}.
This table has a one-to-one relationship with the user table, since every external user also has a unique user id.

\subsubsection{User Group Table}
In our system user groups are just a collection of users. Thus a group has a many-to-many relationship with the user table. The association is done by the \verb=user_group_association= table. This means that a user group can have many users and a user can be a part of many groups. The table only saves the name and a short description of a user group.  User groups can be managed easily from the administrators in the download portal. This is described in more detail in Section~\ref{sec:uidp}. 

\subsubsection{User Right Table}
User rights in our system are different properties, similar to JAVA properties, which can be assigned to different users via the
\verb= user_rights_association= table, or to different user groups via the 
\verb=usergroup_rights_association= table.  Both of these relations are of type many-to-many, which means that each user can have many user rights associated specifically with him, and each user group can have many different rights associated with it. If a user is part of a user group, 
he automatically has all the rights of the user group as well. This is done by joining the following tables on their primary keys:
\verb=user=,  \verb=user_group_association=, \verb=user_group =, \verb=usergroup_rights_association= and \verb=user_right=. However, as we discuss this later on in this section, in our implementation we let Hibernate make all the appropriate joins, as we only work with Java objects. 

User rights have three important attributes. A domain describes a specific area where a property should be applied, e.g., a domain could be the name of a document, which a user is trying to download. The other two parts are a name and a value, which describe the property. We go over our implementation of user rights in more detail in 
Section~\ref{sec:userrights}. 

\subsubsection{Download Document Table}
This table is used to store information about documents for the download portal. A download document is a ZIP file, which contains a WUEBDIFON finished project. Thus our system is unaware of the exact content of the document. However, we do save some meta information, such as name and a note, which are then presented to the user for convenience. In addition, we store the path to the ZIP file, which can be a regular file path or a Samba resource file path.   

\subsubsection{Download Document Log}
In this table we put an entry whenever a user downloads a document form the download portal. This implies that we are able to keep a record of all the documents, which are downloaded by a given user.   

\subsubsection{Book Table}
The book table was part of the ELBS 1.0 database and no major improvements were made to it, except for the fact that 
we added a column to save the number of available copies in the library. The basic purpose of this table is to store information such as the title of the book, where it is located on the file system, as well as an OPAC signature of the book, which will make it easier to integrate the book with the online catalog of the University Library of W\"urzburg.  

\subsubsection{Page Table}
The page table is responsible for storing information about a page. The table was present in ELBS 1.0 but extended in ELBS 1.1. A page in the ELBS system is an encrypted image file. The exact file format is described in Section~\ref{sec:dataprotection}.  The table stores the base name of the image. There is no need to keep the full path in this table, because it can be resolved from the book path and the base name.  As can be seen in Figure~\ref{fig:db} the relationship between book and page is one-to-many, which means that one book can have many different pages. For ELBS 1.1 we extended the page table with the boolean attribute \verb=is_free=, which is set  \verb=true= whenever a page can be downloaded for free, i.e., it does not increment the download counter for a user. Such pages are for example pages form the table of contents.

\subsubsection{Page Download Log Table}
In this table we put an entry whenever a user downloads or prints a page of an ELBS E-Book. Thus we are able to keep a record of all downloaded/printed pages. This is an essential table for the ELBS viewer, since the German copy right law only allows a limited portion of an E-Book to be printed/downloaded.  Moreover, the attribute \verb=is_printed= is set to \verb=true= whenever a user tries to print the page, and set to \verb=false= whenever a user downloads a page in a PDF format. This means that our system is able to distinguish between those two different user requests,  as this was a compulsory requirement. However, this does not affect the fact that a user cannot obtain more than 75\% of a book. 

\subsubsection{ELBS Client Data Table}
This table stores information about the computers, which are allowed to run the ELBS viewer. The information can be comprised of a hard disk number and an IP address, for instance. A more detailed discussion on this topic can be found in Section~\ref{sec:authentication}.

\subsubsection{Random Data Table}
This table stores a random number, which is needed for the authentication of ELBS clients.  More information can be found in 
Section~\ref{sec:authentication}. 

\subsubsection{ELBS View Session Table}
This table holds a unique session ID, which is used to authenticate ELBS clients to view E-Books. The attribute \verb=last_interaction= holds a timestamp value\footnote{For timestamp values in ELBS we use Unix time, which the number of seconds since 00:00:00 UTC on January 1, 1970.},
that is updated after each user interaction with the server. Thus a session is valid only a limited amount of time. It should be noted that this session is used only for viewing purposes and it is not associated with a particular user, but rather with a computer, which runs the ELBS viewer.

\subsubsection{ELBS Download Session Table}
This table holds a unique session ID, which enables ELBS clients to download or print E-Books. This session is associated with a user from the table \verb=User=. The relation between the two tables is of type one-to-one since a user can have only one active session. This table is also associated with a normal viewing session, as we still have to update its timestamp, in order for the user to further be able to
view E-Book pages.  
\newline
As can be seen from Figure~\ref{fig:db}, our database schema is decomposed into many tables. 
When decomposing a database schema, one should rely on the normal forms guidelines.  Normal forms are employed
to avoid or eliminate the three types of data anomalies (insertion, deletion and update
anomalies), which a database may suffer from~\cite[Chapter~14]{bdb1}. Our schema
satisfies the 3rd Normal Form. However, the normalization of a database has some disadvantages as well. The
biggest of which is the fact that we often have to join several tables together in order to achieve the desired result. 
This could have negative impact on the scalability and reliability of a system, since
joining tables involves very large SQL statements, which could become
inconvenient and error prone. However, in our application we rely on Hibernate, and therefore we do not 
use SQL at all. Instead, we use object-relational mapping (ORM), which maps
Java classes to database tables. This is accomplished through the configuration 
of an XML file or by using Java annotations. In our implementation we use Java annotations. The reason for
that is the fact that annotations 
simplify persistence programming with Hibernate, because:
 
\begin{itemize}
	\item	We do not have to keep information about the Java class in an external XML file, 
	which simplifies the debugging process. 
	\item With lots of classes, the XML file can become quite large, unclear and error prone.
\end{itemize}

An example of a Java class that is mapped to a relational database table using annotations
is shown in Listing~\ref{listing:userhibernate}.
For the
sake of simplicity we do not include the methods of the class in the example, as they are simple getters and
setters for accessing the different attributes.
A UML class diagram of all the classes involved in the new object-oriented model of the database, is shown
in Figure~\ref{fig:pojos}. In this model the tables illustrated in Figure~\ref{fig:db} 
are realized as classes. However, we do not need classes for the association tables, 
as they are used only for joining tables, which in this model is done automatically
by Hibernate, based on the information provided in the Java annotations of each class. 

As Listing~\ref{listing:userhibernate} and Figure~\ref{fig:pojos} show, Hibernate 
is able to manage relationships of type one-to-many and many-to-many by using Java collections. 
For example, instead of joining tables to obtain all the user groups where a user is a member, we can just
call the \verb=getUserGroups()= method of a user object. At this point we should mention that, Hibernate
uses two different loading strategies to retrieve associated objects or collections~\cite{whibernate1}. 
First, we can load associated objects \emph{eagerly}. This means associated
objects are loaded by Hibernate using a single SQL statement, thus
the objects are created even if they are not needed. For example, if we load a user object eagerly, this would 
require to load all of its groups and all of the groups' rights. With a large database this could have a
negative impact on the performance of the system. The second type of loading associated objects is
the \emph{lazy} loading, i.e., objects are loaded only when they are accessed for the first time.
In our case this means that Hibernate uses different implementation of the \verb=java.util.List=
interface (among others) that it sends to our class in place of default implementations (such as \verb=ArrayList=). 
When we try to access objects from the list, Hibernate creates a new SQL statement and retrieves them from
the database. This is also the approach we use in our implementation. It should be noted that using lazy loading 
in Hibernate
and Spring is not as transparent to the developer as it may first appear. The reason for that is the fact that it requires keeping track of Hibernate
sessions. Discussing lazy loading in Hibernate, however, is beyond the scope of
this report, additional information on the subject can be found in~\cite{whibernate1} and~\cite{whibernate2}.\newline

\begin{figure}[htp]
	\begin{center}
		\includegraphics[width=\textwidth]{./img/hibernate.pdf}
		\caption{Database as Hibernate Classes}
		\label{fig:pojos}
	\end{center}
\end{figure}

In ELBS we sometimes need an to count rows in a table with specific properties, e.g., the number of downloaded pages of a specific book
for a given user could be calculated with the help of the \verb=page_download_log= table. However, doing this entirely with the help of object mapping would be inefficient, as it would require initializing an object for each row of that table and then counting the appropriate instances. To overcome this and other related issues, we use the The Hibernate Query Language (HQL), which is similar in appearance to SQL. In fact, HQL-queries are translated into SQL-ones, which are then executed by the DBMS.    
Compared with SQL, however, HQL is fully object-oriented and understands notions like inheritance, polymorphism and association~\cite{whibernate3}.

Another very important aspect of our system is the fact that we implemented a test package.
It contains many JUnit tests for testing
different system functionalities, such as accessing, creating and saving 
objects in the database, using Hibernate. In the case where we need to alter the database schema, which is quite
common for Web-applications, we can simply run all the test cases to ensure that our system is compatible
with the new table design.  

\section{User Rights Management}
\label{sec:userrights}
In this section we present our user model, which involves the management of 
users, user groups and user rights (also referred as privileges) in our system. 
In general, user rights authorize users to perform specific tasks, such as 
downloading or printing pages in the ELBS viewer, or downloading documents from the download portal. 

As mentioned in the previous section, user rights in our system are realized by the \verb=UserRight= class,
which maps the \verb=user_rights= table. Each user right has three important attributes. 
A domain describes a specific area where the right should be applied.
For example, a domain can be a document from the download portal, to which a user is trying to get access. 
The other two parts are a name and a value, which describe the property.

A user right can be better understood with the help of an example. 
In the following table there are five different user rights:
	
\begin{center}
\begin{tabular}[h]{|l|l|l|l|}
  \hline
  ID & Domain & Name & Value \\ \hline
  1 & ELBS & BOOK\_DOWNLOAD\_PERCENT & 75 \\  
  2 & ELBS & MAX\_PAGE\_DOWNLOAD & 7 \\
  3 & DP\_12345 & ENABLE & 1  \\ 
  4 & DP\_56789 & MAX\_NR & 10  \\
  5 & DP\_56789 & EXP\_DATE & 2010.12.06  \\ \hline
\end{tabular}
\end{center}

The first user right indicates that the domain of the user right is the ELBS viewer, and that a user can download or print a maximum of 75\% of a book.  The second user right also applies to the ELBS viewer and means that a user can download each page of a book up to 7 times.  The next three user rights have a prefix \verb=DP_= in the domain, which means that they apply to the download portal. Thus, the domain  \verb=DP_12345= must be interpret as follows: the right applies to a document with an ID~=~12345.
This document can be downloaded by the user without any 
further restrictions, since it has the property \emph{ENABLE~=1}. 
The last two user rights are relevant to a document with an ID~=~56789. However, in this case the property is not 
 \emph{ENABLE~=~1}, which indicates that user may download the document, but there are additional restrictions. In fact, in this case the user can download the document only up to 10 times , because or the \emph{MAX\_NR~=10} property. This can be done, however, only until
the 6.12.2010, because the \emph{EXP\_DATE~=2010.12.06} property presents an additional restriction for the time interval.

It is worth mentioning that it is the role of the controller, which processes the HTTP request, to interpret a user right correctly. 

It should be noted that by implementing all the user rights to be stored in a single table we gain great flexibility for our system. Introducing new user rights or user right domains does not require any changes to the existing tables or the source code of server. In fact, our system and database could be used for future projects, 
which require user right management.

 
As we mentioned in the previous section user rights can be assigned to individual users. Furthermore, a user 
can be a member of many different user groups, which also have rights assigned to them. 
User rights that are assigned to a group are applied to all members of the group while they remain members. 
User rights that are assigned to an individual user apply even if he is not part of any group.
Thus, the user's rights are cumulative, which means that the user has more than one set of rights.
This approach 
for assigning user rights is very flexible, but it has some disadvantages
as well, not the least of which is the fact that a user could have a user right conflict.
Conflicting user rights have
the same domain and name but different values. An example of this is illustrated in Figure~\ref{fig:urconflict}. The 
example shows a user who has 4 different rights assigned to him, and all of them restrict the 
download of a document with an ID~=~12345. For example, there is a conflict between \verb=UserRight_A=
and \verb=UserRight_B=, as they specify different expiration dates for the same document. 
\verb=UserRight_C= and \verb=UserRight_D= are also in conflict, as they specify different maximal number
of downloads for the same document.

\begin{figure}[ht]
	\begin{center}
		\includegraphics[width=0.7\textwidth]{./img/user_rights_objects.pdf}
		\caption{Example of Conflicting User Rights}
		\label{fig:urconflict}
	\end{center}
\end{figure}

In general, however, user rights assigned to individual users or to a group do not conflict with the rights assigned to 
another group. Nevertheless, we need to ensure that we can handle conflicts correctly. In order to achieve this we, 
defined a Java interface called \verb=UserRightConflictPolicy=, which is shown in Listing~\ref{listing:urp}. Classes
that implement this interface are called conflict policies, and they should return a set of non-conflicting user rights 
for a given user and a domain. These conflict policies
are then used by the different Spring controllers, in order to choose the appropriate user right for a given task. In
the current version of the server, we implemented a policy class that maximizes the chances of an user to
download a document. This means that in the above example \verb=UserRight_B= should be chosen over \verb=UserRight_A=, and
\verb=UserRight_C= over \verb=UserRight_D=. If a different behavior is desired, one can easily define new policies,
by implementing the \verb=UserRightConflictPolicy= interface.

\begin{lstlisting}[caption={Java Interface UserRightConflictPolicy}, label={listing:urp}]
/**
 * This interface is used for handling conflicts regarding 
 * rights. Conflicting user rights are rights that are 
 * assigned to a user and have the same domain and name, 
 * but  different value. 
 */
public interface UserRightConflictPolicy 
{
	/**
	 * Classes which implement this method should resolve issues
	 * with conflicting user rights. 
	 * @param user A user from the database. 
	 * @param userRights All user rights associated with that user,
	 * 	this also includes all the rights from all the groups, where 
	 * 	the user is a member.  
	 * @param domain The user right domain for which the policy must
	 * 	be applied.  
	 * @return a set of non conflicting user rights for that domain. 
	 */
	Set<UserRight> applyConflictPolicy(User user, 
			List<UserRight> userRights, String domain);
}
\end{lstlisting}

In our System user rights can be managed with the help of the 
administrator user interface in the download portal, which is discussed in Section~\ref{sec:uidp}.

In conclusion, we should point out that our user right model is similar to 
the Role Based Access Control (RBAC) model~\cite{prbac}. 
RBAC is another approach for restricting system access to authorized users.
It permits or limits access to an object, e.g., a document, 
based on the role of the individual trying to access the object. 
The equivalent of a role in our implementation is a user right, though a role does not have
a value associated with it. 
However, in a typical RBAC system roles are static with well-defined access
control privileges, which do not change over time, i.e.,
a user is ether able to gain access to a resource or not. 
On the other hand, in our system restrictions change dynamically. For instance, a user 
might be able to download a document, but only if a maximum number of downloads for that document has not been 
reached by that particular user; or our system could deny a download of a page in the ELBS viewer, if a user
has downloaded too many pages already. Moreover, in the download portal we can
also restrict access to a document temporarily. This is done by assigning an
expiration date for a document to a specific user or a user group. 
A traditional RBAC model does not support such temporal semantics 
~\cite{prbac2}, as it would require dynamically assigning and removing roles from user groups, which
could potentially introduce conflicts with other users' roles. More about these issues can be read in~\cite{prbac2} and~\cite{prbac3}.

\input{./tex/ui}
